package com.android.webserver;

import java.util.List;

import com.android.webserver.db.DatabaseOpenHelper;
import com.android.webserver.db.WebApplication;
import com.android.webserver.security.Session;
import com.android.webserver.tornado.Tornado;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

/**
 * @author Baptiste GOURDIN
 *
 */
public class WebServerService extends Service
{
	private Tornado						server;
	public DatabaseOpenHelper	db;
	public static boolean			RUNNING		= false;
	public Session						sessions;
	public static final boolean DEBUG = true;

	@Override
	public void onCreate()
	{
		db = new DatabaseOpenHelper(this);
		sessions	= new Session(this);
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		RUNNING = true;
		server = new Tornado(this);
		server.start();

		Log.i("WebServer", "Service started");
		listApps();
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy()
	{
		RUNNING = false;
		Log.i("WebServer", "Service stopped");
		/// FIXME : kill threads and unbind ports
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		
		
		return null;
	}
	
	
	public void listApps()
	{
		PackageManager pm = this.getPackageManager();
		List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_PROVIDERS);
		DatabaseOpenHelper db = new DatabaseOpenHelper(this);

		for (PackageInfo p : packages)
		{
			String packageName = p.packageName;
			ProviderInfo[] provs = p.providers;
			if (provs != null)
				for (ProviderInfo prov : provs)
				{
					if ((prov.readPermission != null) && (prov.readPermission.equals("com.android.webserver.WEB_SERVER")))
					{
						ContentResolver cr = this.getContentResolver();
						Cursor c = cr.query(Uri.parse("content://" + prov.authority), new String[] {"registration" }, null, null, null);
						if ((c != null) && (c.getCount() > 0))
						{
							c.moveToFirst();
							String path = c.getString(0);
							String pass = c.getString(1);
							WebApplication webApp = new WebApplication(p.packageName, path, prov.authority);
							if (!pass.equals(""))
								webApp.setPassword(pass);

							db.registerApplication(webApp);
						}
					}
				}
		}
		db.close();
	}

}
